<route lang="json5">
{
  style: {
    navigationBarTitleText: '课程详情',
  },
}
</route>
<template>
  <view class="entire">
    <image
      style="z-index: -10; position: fixed; top: 0; width: 100vw; height: 100vh"
      :src="listBg"
      mode="aspectFill"
    />
    <!--视频组件-->
    <video
      autoplay="true"
      v-if="video.videoOpen"
      style="z-index: 100; position: fixed; top: 0; width: 100vw; height: 500rpx"
      id="myVideo"
      :src="video.url"
      controls
      @timeupdate="recordVideoProgress"
    />
    <button
      v-if="video.videoOpen"
      size="mini"
      style="
        color: white;
        background-color: #1b5b93;
        z-index: 100;
        position: fixed;
        top: 520rpx;
        right: 20rpx;
      "
      @click="closeVideo"
    >
      关闭视频
    </button>
    <view class="div1">
      <view class="info-card">
        <image :src="pageData.courseDetail.frontImageUrl" style="width: 700rpx; height: 400rpx" />
        <view class="info">
          <image
            style="width: 35rpx; height: 26rpx; margin-left: 20rpx"
            src="/static/images/icons/icon_people.png"
          />
          <view style="min-width: 200rpx; margin-left: 20rpx">
            学习人数: {{ pageData.courseDetail.look_num }}
          </view>
          <image
            v-if="!pageData.isCollect"
            @click="handleCollect()"
            style="width: 35rpx; height: 35rpx; margin-left: 150rpx"
            src="/static/images/icons/icon_star_gray.png"
          />
          <image
            v-else
            @click="handleCollect()"
            style="width: 35rpx; height: 35rpx; margin-left: 150rpx"
            src="/static/images/icons/icon_star_blue.png"
          />
          <view
            @click="handleCollect()"
            v-if="!pageData.isCollect"
            style="min-width: 100rpx; margin-left: 10rpx"
          >
            收藏
          </view>
          <view
            @click="handleCollect()"
            v-else
            style="margin-left: 10rpx; min-width: 100rpx; color: #11487a"
          >
            收藏
          </view>
          <image
            v-if="!pageData.isLike"
            @click="handleLike()"
            style="width: 35rpx; height: 35rpx; margin-left: 20rpx"
            src="/static/images/icons/icon_like_gray.png"
          />
          <image
            v-else
            @click="handleLike()"
            style="width: 35rpx; height: 35rpx; margin-left: 20rpx"
            src="/static/images/icons/icon_like_blue.png"
          />
          <view @click="handleLike()" v-if="!pageData.isLike" style="margin-left: 10rpx">赞</view>
          <view @click="handleLike()" v-else style="margin-left: 10rpx; color: #11487a">赞</view>
        </view>
      </view>
    </view>
    <scroll-view
      scroll-y="true"
      enable-flex="true"
      class="div2"
      :style="{ height: pageData.div2Height + 'px' }"
    >
      <view class="title">
        目录
        <view style="width: 80rpx; height: 7rpx; background-color: #1b5b93" />
      </view>
      <!--视频列表-->
      <view @click="openVideo(item)" v-for="(item, index) in pageData.CourseList" :key="index">
        <SubCourseItem :subCourse="item" />
      </view>
      <!-- 考试列表 -->
      <view v-for="(item, index) in pageData.ExamList" :key="index" @click="openExam(item)">
        <ExamItem :exam="item" />
      </view>
      <!--加载中，到底啦横幅-->
      <view style="margin-top: 30rpx; padding-bottom: 50rpx">
        <wd-divider color="black">{{ pageData.loading ? '加载中...' : '已经到底了' }}</wd-divider>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import SubCourseItem from '@/components/CourseItem/SubCourseItem.vue'
import ExamItem from '@/components/ExamItem/ExamItem.vue'
import { MixedResourceItem } from '@/service/mixedResource/mixedResource'
import {
  CourseDetails,
  getCourseDetails,
  getCourseWare,
  getCourseWareList,
  getVideoFile,
  goInExam,
  updateMinimumTime,
  updateProgress,
} from '@/service/courseWare/courseWare'
import { collectResource } from '@/service/collection/collection'
import { listBg } from '@/static/imgMap'

const video = reactive({
  videoOpen: false,
  videoContext: null,
  url: null,
  initialTime: 0, // 单位是秒，是直接给video用的
  progress: 0, // 单位是百分数
  learnDuration: 0,
})
const pageData = reactive({
  isLike: false, // 在此控制收藏和点赞
  isCollect: false,
  number: 114,
  div2Height: 600,
  courseDetail: {} as CourseDetails,
  data: {} as MixedResourceItem,
  CourseList: [],
  ExamList: [],
  loading: false,
})
const openExam = (item) => {
  goInExam(pageData.courseDetail.courseId, pageData.courseDetail.recordId, item.exampaperId).then(
    (res) => {
      if (res.code === 200) {
        const senduserId = res.data.senduserId
        if (item.isCanGo === 0) {
          // 查看之前考试的解析
          uni.navigateTo({
            url: `/pages-sub/exam/examRoom/userAnswerRoom?id=` + senduserId,
          })
        } else {
          // 进入考试
          uni.navigateTo({
            url: `/pages-sub/exam/examRoom/examRoom?id=` + senduserId + `&showResults=1`,
          })
        }
      } else {
        uni.showToast({
          title: res.message,
          icon: 'none',
        })
      }
    },
  )
}
let intervalId: number | undefined
let intervalId2: number | undefined
const openVideo = async (item) => {
  try {
    const response = await getVideoFile(item.packId)
    // 如果文件后缀不是MP4，就不显示
    if (response.RecordCount > 0 && response.DataList[0].Url.length > 0) {
      if (response.DataList[0].Suffix !== 'mp4') {
        console.error('视频不是MP4文件')
        uni.showToast({
          title: '视频不是MP4文件: ' + response.DataList[0].Suffix,
          icon: 'none',
        })
        return
      }
      video.url = response.DataList[0].Url[0].ConvertFileUrl
      item.learnDuration = Number(response.DataList[0].LearnDuration)
      video.initialTime = item.progress
      video.learnDuration = item.learnDuration
      console.log('video.learnDuration:', video.learnDuration)
      video.videoOpen = true
      video.videoContext = uni.createVideoContext('myVideo')
      setTimeout(() => {
        video.videoContext.seek(video.initialTime)
      }, 500)

      // 每隔5s上传进度
      const courseWare = await getCourseWare(item.wareId)
      intervalId = setInterval(() => {
        const currentTime = video.videoContext.currentTime
        updateProgress({
          courseId: pageData.courseDetail.courseId,
          wareRecordId: courseWare.data.len.id,
          progress: currentTime.toFixed(0),
          allprogress: video.learnDuration,
        })
      }, 5000)
      intervalId2 = setInterval(() => {
        updateMinimumTime({
          courseId: pageData.courseDetail.courseId,
          wareRecordId: courseWare.data.len.id,
          timeLen: 5,
        })
      }, 5000)
    } else {
      uni.showToast({
        title: '没有视频文件',
        icon: 'none',
      })
    }
  } catch (error) {
    console.error('Error fetching video file:', error)
  }
}
const closeVideo = () => {
  video.videoOpen = false
}
// 记录视频看到的进度
const recordVideoProgress = (e) => {
  video.progress = (e.detail.currentTime / video.learnDuration) * 100
  video.videoContext.currentTime = e.detail.currentTime
}
const handleLike = () => {
  // todo 课程点赞收藏
  pageData.isLike = !pageData.isLike
}
const handleCollect = async () => {
  collectResource(pageData.data.resId, 0).then((res) => {
    if (res.code === 200) {
      uni.showToast({
        title: res.message | '操作成功',
        icon: 'none',
      })
      pageData.isCollect = !pageData.isCollect
    } else {
      uni.showToast({
        title: res.message,
        icon: 'none',
      })
    }
  })
}
onMounted(async () => {
  const response = await getCourseDetails({ id: pageData.data.resId })
  // 使用 Promise.all 处理异步操作
  pageData.CourseList = await Promise.all(
    response.data.wareList.map(async (item) => {
      const courseWare = await getCourseWare(item.wareId) // 等待异步结果
      return {
        progress: courseWare.data.len.progress,
        title: item.wareName,
        progressPercent: courseWare.data.len.progressPercent,
        packId: item.packId,
        wareId: item.wareId,
      }
    }),
  )

  // 将examList赋值给pageData.ExamList 字段转化成 ExamListItem
  pageData.ExamList = response.data.examList.map((item) => {
    return {
      examTitle: item.examTitle,
      testTimes: item.testTimes,
      timeLength: item.timeLength,
      allowTimes: item.allowTimes,
      exampaperId: item.exampaperId,
      isCanGo: item.isCanGo,
      isPass: item.isPass,
    }
  })

  pageData.courseDetail = response.data.course
  pageData.isLike = response.data.course.isLike
  pageData.isCollect = response.data.course.isCollection

  uni.getSystemInfo({
    success(res) {
      const screenHeight = res.windowHeight
      uni
        .createSelectorQuery()
        .select('.div1')
        .boundingClientRect((data) => {
          if ('height' in data) {
            pageData.div2Height = screenHeight - data.height
          }
        })
        .exec()
    },
  })
})

onLoad((options) => {
  // 页面跳转参数接收
  pageData.data = JSON.parse(decodeURIComponent(options.data))
  console.log(pageData.data)
})
onUnmounted(() => {
  if (intervalId !== undefined) {
    clearInterval(intervalId)
  }
  if (intervalId2 !== undefined) {
    clearInterval(intervalId2)
  }
})
</script>

<style scoped lang="scss">
.entire {
  width: 100%;
  .div1 {
    width: 100%;
    height: 530rpx;
    background-color: #f2f2f2;
    padding-top: 30rpx;
    .info-card {
      margin-left: 25rpx;
      margin-bottom: 60rpx;
      width: 700rpx;
      height: 480rpx;
      border-radius: 25rpx;
      background-color: white;
      overflow: hidden;
      .info {
        color: grey;
        display: flex;
        width: 700rpx;
        height: 80rpx;
        align-items: center;
      }
    }
  }
  .div2 {
    display: flex;
    flex-direction: column;
    width: 100%;
    overflow-y: scroll;
    .title {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      width: 100%;
      height: 100rpx;
    }
  }
}
.is-hover {
  background-color: #0d2b47;
}
</style>
